package com.scheduling.order.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scheduling.order.entity.OrderItem;
import com.scheduling.order.entity.dto.OrderItemDTO;
import com.scheduling.order.mapper.OrderItemMapper;
import com.scheduling.order.service.IOrderItemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单项服务实现类
 *
 * @author 开发团队
 * @since 2025-05-29
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OrderItemServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem> implements IOrderItemService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<OrderItemDTO> createOrderItems(String orderId, List<OrderItemDTO> orderItems) {
        log.info("创建订单项，订单ID: {}, 数量: {}", orderId, orderItems.size());

        if (StrUtil.isBlank(orderId)) {
            throw new IllegalArgumentException("订单ID不能为空");
        }

        if (orderItems == null || orderItems.isEmpty()) {
            throw new IllegalArgumentException("订单项列表不能为空");
        }

        List<OrderItemDTO> result = new ArrayList<>();

        for (OrderItemDTO orderItemDTO : orderItems) {
            // 创建订单项实体
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(orderId);
            orderItem.setProductId(orderItemDTO.getProductId());
            orderItem.setQuantity(orderItemDTO.getQuantity());
            orderItem.setPriority(orderItemDTO.getPriority());
            orderItem.setProducedQuantity(0); // 初始已生产数量为0
            orderItem.setStatus(OrderItem.ItemStatus.PENDING);

            boolean saved = this.save(orderItem);
            if (!saved) {
                throw new RuntimeException("订单项保存失败");
            }

            // 查询订单项详情并添加到结果中
            OrderItemDTO createdItem = this.getOrderItemDetail(orderItem.getOrderItemId());
            result.add(createdItem);
        }

        log.info("订单项创建成功，数量: {}", result.size());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderItemDTO updateOrderItem(OrderItemDTO orderItemDTO) {
        log.info("更新订单项: {}", orderItemDTO.getOrderItemId());

        if (StrUtil.isBlank(orderItemDTO.getOrderItemId())) {
            throw new IllegalArgumentException("订单项ID不能为空");
        }

        // 检查订单项是否存在
        OrderItem existingItem = this.getById(orderItemDTO.getOrderItemId());
        if (existingItem == null) {
            throw new RuntimeException("订单项不存在: " + orderItemDTO.getOrderItemId());
        }

        // 更新订单项
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderItemId(orderItemDTO.getOrderItemId());
        orderItem.setProductId(orderItemDTO.getProductId());
        orderItem.setQuantity(orderItemDTO.getQuantity());
        orderItem.setPriority(orderItemDTO.getPriority());

        // 如果传入了已生产数量，则更新
        if (orderItemDTO.getProducedQuantity() != null) {
            orderItem.setProducedQuantity(orderItemDTO.getProducedQuantity());

            // 根据已生产数量自动更新状态
            if (orderItemDTO.getProducedQuantity() >= orderItemDTO.getQuantity()) {
                orderItem.setStatus(OrderItem.ItemStatus.COMPLETED);
            } else if (orderItemDTO.getProducedQuantity() > 0) {
                orderItem.setStatus(OrderItem.ItemStatus.IN_PRODUCTION);
            } else {
                orderItem.setStatus(OrderItem.ItemStatus.PENDING);
            }
        }

        boolean updated = this.updateById(orderItem);
        if (!updated) {
            throw new RuntimeException("订单项更新失败");
        }

        log.info("订单项更新成功: {}", orderItemDTO.getOrderItemId());
        return this.getOrderItemDetail(orderItemDTO.getOrderItemId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrderItem(String orderItemId) {
        if (StrUtil.isBlank(orderItemId)) {
            throw new IllegalArgumentException("订单项ID不能为空");
        }

        boolean deleted = this.removeById(orderItemId);
        if (deleted) {
            log.info("订单项删除成功: {}", orderItemId);
        }

        return deleted;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteOrderItemsByOrderId(String orderId) {
        if (StrUtil.isBlank(orderId)) {
            throw new IllegalArgumentException("订单ID不能为空");
        }

        LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItem::getOrderId, orderId);

        List<OrderItem> orderItems = this.list(queryWrapper);
        int count = orderItems.size();

        if (count > 0) {
            boolean deleted = this.remove(queryWrapper);
            if (!deleted) {
                throw new RuntimeException("删除订单项失败");
            }
        }

        log.info("删除订单项完成，订单ID: {}, 删除数量: {}", orderId, count);
        return count;
    }

    @Override
    public OrderItemDTO getOrderItemDetail(String orderItemId) {
        if (StrUtil.isBlank(orderItemId)) {
            throw new IllegalArgumentException("订单项ID不能为空");
        }

        OrderItemDTO orderItemDTO = baseMapper.selectOrderItemDetailById(orderItemId);
        if (orderItemDTO == null) {
            throw new RuntimeException("订单项不存在: " + orderItemId);
        }

        return orderItemDTO;
    }

    @Override
    public List<OrderItemDTO> getOrderItemsByOrderId(String orderId) {
        if (StrUtil.isBlank(orderId)) {
            return new ArrayList<>();
        }

        return baseMapper.selectOrderItemsByOrderId(orderId);
    }

    @Override
    public List<OrderItemDTO> getOrderItemsByStatus(String status) {
        return baseMapper.selectOrderItemsByStatus(status);
    }

    @Override
    public List<OrderItemDTO> getOrderItemsByProductId(String productId) {
        if (StrUtil.isBlank(productId)) {
            return new ArrayList<>();
        }

        return baseMapper.selectOrderItemsByProductId(productId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProducedQuantity(String orderItemId, Integer producedQuantity) {
        if (StrUtil.isBlank(orderItemId)) {
            throw new IllegalArgumentException("订单项ID不能为空");
        }

        if (producedQuantity == null || producedQuantity < 0) {
            throw new IllegalArgumentException("已生产数量不能为空或负数");
        }

        // 查询订单项信息
        OrderItem orderItem = this.getById(orderItemId);
        if (orderItem == null) {
            throw new RuntimeException("订单项不存在: " + orderItemId);
        }

        // 更新已生产数量
        LambdaUpdateWrapper<OrderItem> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(OrderItem::getOrderItemId, orderItemId)
                .set(OrderItem::getProducedQuantity, producedQuantity);

        // 根据生产数量自动更新状态
        String newStatus;
        if (producedQuantity >= orderItem.getQuantity()) {
            newStatus = OrderItem.ItemStatus.COMPLETED;
        } else if (producedQuantity > 0) {
            newStatus = OrderItem.ItemStatus.IN_PRODUCTION;
        } else {
            newStatus = OrderItem.ItemStatus.PENDING;
        }
        updateWrapper.set(OrderItem::getStatus, newStatus);

        boolean updated = this.update(updateWrapper);
        if (updated) {
            log.info("订单项生产数量更新成功: {} -> {} (状态: {})", orderItemId, producedQuantity, newStatus);
        }

        return updated;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderItemStatus(String orderItemId, String status) {
        if (StrUtil.isBlank(orderItemId)) {
            throw new IllegalArgumentException("订单项ID不能为空");
        }

        LambdaUpdateWrapper<OrderItem> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(OrderItem::getOrderItemId, orderItemId)
                .set(OrderItem::getStatus, status);

        boolean updated = this.update(updateWrapper);
        if (updated) {
            log.info("订单项状态更新成功: {} -> {}", orderItemId, status);
        }

        return updated;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchUpdateOrderItemStatus(List<String> orderItemIds, String status) {
        if (orderItemIds == null || orderItemIds.isEmpty()) {
            return 0;
        }

        LambdaUpdateWrapper<OrderItem> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(OrderItem::getOrderItemId, orderItemIds)
                .set(OrderItem::getStatus, status);

        boolean updated = this.update(updateWrapper);
        int updatedCount = updated ? orderItemIds.size() : 0;

        log.info("批量更新订单项状态: {} 个订单项 -> {}", updatedCount, status);
        return updatedCount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean incrementProducedQuantity(String orderItemId, Integer incrementQuantity) {
        if (StrUtil.isBlank(orderItemId)) {
            throw new IllegalArgumentException("订单项ID不能为空");
        }

        if (incrementQuantity == null || incrementQuantity <= 0) {
            throw new IllegalArgumentException("增加数量必须大于0");
        }

        // 查询当前已生产数量
        OrderItem orderItem = this.getById(orderItemId);
        if (orderItem == null) {
            throw new RuntimeException("订单项不存在: " + orderItemId);
        }

        int currentProduced = orderItem.getProducedQuantity() != null ? orderItem.getProducedQuantity() : 0;
        int newProduced = currentProduced + incrementQuantity;

        // 不能超过订单数量
        if (newProduced > orderItem.getQuantity()) {
            newProduced = orderItem.getQuantity();
        }

        return this.updateProducedQuantity(orderItemId, newProduced);
    }

    @Override
    public boolean isOrderItemCompleted(String orderItemId) {
        if (StrUtil.isBlank(orderItemId)) {
            return false;
        }

        OrderItem orderItem = this.getById(orderItemId);
        if (orderItem == null) {
            return false;
        }

        return OrderItem.ItemStatus.COMPLETED.equals(orderItem.getStatus()) ||
                (orderItem.getProducedQuantity() != null &&
                        orderItem.getProducedQuantity() >= orderItem.getQuantity());
    }

    @Override
    public List<OrderItemDTO> getPendingOrderItems() {
        return this.getOrderItemsByStatus(OrderItem.ItemStatus.PENDING);
    }

    @Override
    public List<OrderItemDTO> getHighPriorityOrderItems() {
        LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItem::getPriority, OrderItem.Priority.HIGH)
                .in(OrderItem::getStatus, OrderItem.ItemStatus.PENDING, OrderItem.ItemStatus.IN_PRODUCTION)
                .orderByAsc(OrderItem::getCreateTime);

        List<OrderItem> items = this.list(queryWrapper);
        List<OrderItemDTO> result = new ArrayList<>();

        for (OrderItem item : items) {
            OrderItemDTO dto = baseMapper.selectOrderItemDetailById(item.getOrderItemId());
            if (dto != null) {
                result.add(dto);
            }
        }

        return result;
    }
} 